package com.wquick.base.camerax

import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver


@Composable
fun CameraXCompose(cameraXHolder: CameraXHolder, openBack: Boolean = true) {

    val ctx = LocalContext.current
    val lifecycleOwner = LocalLifecycleOwner.current

    val cameraProviderFeature = remember { ProcessCameraProvider.getInstance(ctx) }
    val imageCapture = remember { ImageCapture.Builder().build() }

    AndroidView(
        factory = { context ->
            val previewView = PreviewView(context).apply {
                scaleType = PreviewView.ScaleType.FIT_CENTER
            }
            val preview = Preview.Builder().build()
            val selector = CameraSelector.Builder()
                .requireLensFacing(if (openBack) CameraSelector.LENS_FACING_BACK else CameraSelector.LENS_FACING_FRONT)
                .build()
            preview.setSurfaceProvider(previewView.surfaceProvider)
            try {
                cameraXHolder.camera = cameraProviderFeature.get().bindToLifecycle(lifecycleOwner, selector, preview, imageCapture)
                cameraXHolder.imageCapture = imageCapture
            } catch (e: Exception) {
                e.printStackTrace()
            }
            previewView
        },
        modifier = Modifier.fillMaxSize()
    )

    val lifecycle = LocalLifecycleOwner.current.lifecycle
    val lifecycleObserver = remember {
        LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_START -> {

                }

                Lifecycle.Event.ON_STOP -> {

                }

                Lifecycle.Event.ON_DESTROY -> {

                }

                else -> {}
            }
        }
    }
    DisposableEffect(key1 = lifecycle, key2 = lifecycleObserver, effect = {
        lifecycle.addObserver(lifecycleObserver)
        onDispose {
            lifecycle.removeObserver(lifecycleObserver)
        }
    })

}

